package com.chen.configuration;


import com.chen.dao.UserMapper;
import com.chen.entity.User;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.TimeUnit;


//拦截器 拦截全部请求
@Component
public class Interceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String email = request.getParameter("email");
        //登录操作
        String state;
        if (requestURI.contains("loginUser")) {
            //登录操作
            state = this.userMapper.queryStateByEmail(email);
            if ("0".equals(state)) {
                throw new Exception("状态异常，无法登陆，请联系管理员");
            } else {
                return true;
            }
        } else {
            //非登录操作
            try {
                state = this.stringRedisTemplate.opsForValue().get(email);
            } catch (Exception e) {
                throw new Exception("登录已过期，请重新登录");
            }
        }
        if (state == null) {
            throw new Exception("登录已过期，请重新登录");
        } else if ("0".equals(state)) {
            throw new Exception("状态异常，无法登陆，请联系管理员");
        } else {
            this.stringRedisTemplate.opsForValue().set(email, "1", 30, TimeUnit.MINUTES);
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
